import { Service } from 'egg';

export interface Category {
  name: string
  id: number
  createAt: string
  updateAt: string
  author: string
  categoryId: number
}

export default class CategoryService extends Service {
  public async create(name: string) {
    const { app, ctx } = this;
    const existCategories = await app.mysql.select('categories', { where: { name } });
    if (existCategories.length !== 0) return { status: 400, error: '分类名称已经存在！' };
    const { authorization } = ctx.request.headers;
    const { username }: any = ctx.app.jwt.decode((authorization as string).toString());
    await app.mysql.insert('categories', {
      name,
      author: username,
      createAt: ctx.helper.getCreateAt(),
      updateAt: ctx.helper.getCreateAt(),
    });
    const categories = await app.mysql.select('categories', { where: { name } });
    const category = categories[0] as Category;
    return {
      name,
      id: category.id,
      createAt: category.createAt,
      updateAt: category.updateAt,
      author: category.author,
      categoryId: category.categoryId,
    };
  }

  public async find() {
    const { app } = this;
    const categories = await app.mysql.select('categories');
    return categories as Category[];
  }
}
